<template>
  <a-modal :title="title" style="top: 100px;" :visible="true" width="1500px" @cancel="handleCancel">
    <div class="tips">
    </div>
    <a-table class="product-table" :rowKey="row => row.id" :dataSource="list" bordered :pagination="false" size="small">

      <a-table-column title="序号" width="20px">
        <template slot-scope="text, record, index">
          <div>{{ index+1 }}</div>
        </template>
      </a-table-column>

      <a-table-column title="集换礼包标题" width="160px">
        <template slot-scope="row">
          <span>{{row.title}}</span>
        </template>
      </a-table-column>
      <a-table-column title="需收集sku_id列表" width="140px">
        <template slot-scope="row">
          <span>{{row.activity_sku_ids}}</span>
        </template>
      </a-table-column>
      <a-table-column title="回收价" width="100px">
        <template slot-scope="row">
          <div>
            <PriceDisplay :info="row"></PriceDisplay>
          </div>
        </template>
      </a-table-column>
      <a-table-column title="显示零售价" width="100px">
        <template slot-scope="row">
          <div>
            <PriceDisplay :info="row" prefix="display_"></PriceDisplay>
          </div>
        </template>
      </a-table-column>      
      <a-table-column title="礼包库存" width="80px">
        <template slot-scope="row">
          <span>{{row.stock}}</span>
        </template>
      </a-table-column>
      <a-table-column title="集换记录" width="80px">
        <template slot-scope="row">
          <a href="javascript:;" @click="handleEditLog(row)">
            <span class="">{{row.sales}}</span>
          </a>
        </template>
      </a-table-column>
      
      <a-table-column title="排序" width="80px">
        <template slot-scope="row">
          <div>
            <span>{{ row.list_weight || 0 }}&nbsp;</span>
            <a-popover title="排序" trigger="click" v-model="row.visible">
              <template slot="content">
                <div style="display:flex;">
                  <a-input v-model="listWeight" placeholder="请输入" autofocus style="margin-right:10px;width:120px;" size="small"></a-input>
                  <a-button type="primary" size="small" @click="handleUpdateListWeight(row)">保存</a-button>
                </div>
              </template>
              <span><a href="javascript:;">
                  <a-icon type="edit" /></a></span>
            </a-popover>
          </div>
        </template>
      </a-table-column>
      <a-table-column title="活动倒计时" width="80px">
        <template slot-scope="row">
          <div>
            <span>{{ formatTimestamp(row.expira_at*1000) || 0 }}&nbsp;</span>
            <a-popover title="活动倒计时" trigger="click" v-model="row.exinput">
              <template slot="content">
                <!-- <div style="display:flex;">
                  <a-input v-model="expira_at" placeholder="请输入" autofocus style="margin-right:10px;width:120px;" size="small"></a-input>
                  <a-button type="primary" size="small" @click="handleUpdateexpira_at(row)">保存</a-button>
                </div> -->
                <a-date-picker 
                format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabled-time="disabledDateTime"
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                @ok="panelChangetIME"
                v-model="row.expira_at" 
                @change="panelChangetIMEChange(row)"
      
    />
              </template>
              <span><a href="javascript:;">
                  <a-icon type="edit" /></a></span>
            </a-popover>
          </div>
        </template>
      </a-table-column>
      <!-- <a-table-column title="是否开启活动倒计时" width="80px" v-if="info.is_show_expira === 0">
        <template slot-scope="row">
          <span>
            <i-switch :active="row.is_show_expira || 1" v-model="row.is_show_expira" size="small" @change="is_Show_Change($event, row)"></i-switch>
          </span>
        </template>
      </a-table-column>
      <a-table-column title="是否开启活动倒计时" width="80px" v-else>
        <template slot-scope="row">
          <span>
            <i-switch :active="row.is_show_expira || 1" v-model="row.is_show_expira" size="small" disabled></i-switch>
          </span>
        </template>
      </a-table-column> -->
      <a-table-column title="是否开启活动倒计时" width="80px" >
        <template slot-scope="row">
          <span>
            <i-switch :active="row.is_show_expira || 1 " v-model="row.is_show_expira" size="small" @change="is_Show_Change($event, row)"></i-switch>
          </span>
        </template>
      </a-table-column>
      <a-table-column title="上下架" width="80px" v-if="info.status1 === 0">
        <template slot-scope="row">
          <span>
            <i-switch :active="row.status || 1" v-model="row.status" size="small" @change="statusChange($event, row)"></i-switch>
          </span>
        </template>
      </a-table-column>
      <a-table-column title="上下架" width="80px" v-else>
        <template slot-scope="row">
          <span>
            <i-switch :active="row.status || 1" v-model="row.status" size="small" disabled></i-switch>
          </span>
        </template>
      </a-table-column>
      
      <a-table-column title="操作" width="80px">
        <template slot-scope="row">
          <a href="javascript:;" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical" />
           <a href="javascript:;" @click="handleDelete(row)">删除</a>
        </template>
      </a-table-column>
    </a-table>
    <template slot="footer">
      <div class="btn-c">
        <a-button type="primary" class="add" @click="handleCreate">
          新增一个
        </a-button>
        <div style="flex-grow: 1;"></div>

        <a-button key="back" @click="handleCancel">关闭</a-button>
        <!-- <a-button key="submit" type="primary" @click="handleSave">
          保存
        </a-button> -->
      </div>
    </template>
    <EditLordSkuList :info="current" v-if="isEditLordSkuList" @refresh="initList" @close="isEditLordSkuList = false"></EditLordSkuList>
     <a-modal title="集换记录" style="top: 100px;" :visible="isGiftRecord" width="1200px"
           @cancel="isGiftRecord = false" :footer="null">
    <GiftRecord v-if="isGiftRecord" :list_record="list_record" @cancel="isGiftRecord = false"></GiftRecord>
    </a-modal>
  </a-modal>
</template>
<script>
  import UploadImages from '@/components/UploadImages/UploadImages'
  import iSwitch from '@/components/ISwitch/ISwitch'
  import ISkuType from '@/components/ISkuType/ISkuType'
  import GiftRecord from './GiftRecord.vue'
  import moment from 'moment';
  export default {
    components: {
      UploadImages,
      iSwitch,
      ISkuType,
      GiftRecord
    },
    props: {
      info: {
        type: Object,
        default () {
          return {}
        }
      },
      currentSkuLevel: {
        type: Number,
        default () {
          return 1
        }
      }
    },
    data() {
      return {
        uuidPen:'',
        disabledDate:'',
        disabledDateTime:'',
        isGiftRecord: false,
        list_record: {},
        current: {},
        isEditLordSkuList: false,
        page: 1,
        per_page: 10,
        total: 0,
        list: [],
        listWeight: '',
        expira_at:'',
        expira_atTime:'',
        // is_show_expira:0,
        frame: [
          {
            title: '集换礼包标题',
            key: 'title',
            type: 'input',
            newline: true,
            required: true,
            tips: 'tab标签小标题',
          },
          {
            title: '集换奖品标题',
            key: 'sku_title',
            type: 'input',
            newline: true,
            required: true,
            tips: '显示在页面顶部的大标题',
          },
          {
            title: '本次集换商品',
            key: 'sku_type',
            type: 'radio',
            default: 1,
            required: true,
            span: 24,
            options: [{
                title: '无绑定',
                value: 1
              },
              {
                title: '绑定商城中的商品',
                value: 2
              },
              {
                title: '平台虚拟资产',
                value: 3
              }
            ],
            tips: ''
          },
          {
            title: '绑定商品',
            key: 'product_id',
            type: 'product_id',
            auto_fill_fields: {
              'title': 'sku_title',
              'thumb': 'thumb',
              'number': 'number',
              'money_price': ['money_price','display_money_price'],
              'score_price': 'score_price'
            },
            where: {
              sku_type: 2
            }
          },
          {
            title: '绑定虚拟资产',
            key: 'assets',
            type: 'assets',
            where: {
              sku_type: 3
            }
          },
          {
            title: '封面',
            key: 'thumb',
            type: 'image'
          },
          {
            title: '本礼包需要集齐的SKU_ID列表',
            key: 'activity_sku_ids',
            type: 'activity_sku_ids',
            activity_id: this.info.id,
            newline: true,
            required: true,
          },
          {
            title: '回收价',
            key_prefix: '',
            type: 'mix_price',
            tips: '价值用于返售时作为返售原价进行折扣计算',
            newline: true,
            required: true,
          },
          {
            title: '显示零售价',
            key: 'display_money_price',
            type: 'price',
            tips: '仅用于显示',
            newline: true,
            required: true,
          },
          {
            title: '奖品开启返售',
            key: 'is_return_saleable',
            type: 'boolean',
            newline: true,
            tips: '开启后集换商品可返售'
          },          
          {
            title: '库存',
            key: 'stock',
            type: 'number',
            suffix: '',
            tips: '',
            newline: true,
            required: true,
          },
          {
            title: '上下架',
            key: 'status',
            type: 'boolean',
            newline: true
          },
        ],
        frame2: [
          {
            title: '开奖时间',
            key: 'end_at',
            type: 'date',
            newline: true,
            required: true,
            tips: '新版逻辑开始时间=开奖时间-间隔时间',
          },
          {
            title: '间隔时间',
            key: 'interval_time',
            type: 'number',
            default: 24,
            newline: true,
            required: true,
            suffix: '单位(小时)',
          },
          {
            title: '次数',
            key: 'num',
            type: 'number',
            default: 7,
            newline: true,
            required: true,
            suffix: '每天连续',
          },
          {
            title: '领主标记SKU_ID',
            key: 'sku_id',
            type: 'number',
            suffix: '',
            tips: '',
            newline: true,
            required: true,
          },
          {
            title: '规则文字',
            key: 'rule',
            type: 'textarea',
            placeholder: '一行一个说明',
            newline: true,
            tips: '不填则使用默认。 一行一个说明，不需要加序号。'
          },
        ]
      }
    },
    computed: {
      title() {
        return '集换礼包列表'
      },
      pagination() {
        return {
          defaultPageSize: this.per_page,
          defaultCurrent: this.page,
          total: this.total,
          onChange: (e) => {
            this.page = e
            // this.per_page = e.pageSize
            this.fetchData()
          }
        }
      }
    },
    watch: {
      uuid() {
        this.initList()
      },
    },
    created() {
      this.initList()
    },
    methods: {
      moment,
       formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
      formatDate(value) {
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      this.expira_atTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
this.timestampFromDate(this.expira_atTime)
      // console.log(this.expira_at)
      
},
timestampFromDate(dateString) {
   this.expira_at = new Date(dateString).getTime(); 
   console.log(this.expira_at)
   this.$http.put(`/kapaishes/${this.uuidPen}/gift`, {
          type: 'update',
          attributes: {
            expira_at: this.expira_at/1000
          }
        }).then(res => {
          this.initList()
          // this.$iForm.hide()
        })
 

   },
      handleUpdateexpira_at(row){
        console.log("row",row)
        row.expira_at=Number(this.expira_at)
        row.exinput=false
        this.expira_at=''
      },
      disabledDate(current) {
        console.log("current",current);
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    },

    disabledDateTime() {
      console.log("151");
      return {
        disabledHours: () => this.range(0, 24).splice(4, 20),
        disabledMinutes: () => this.range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    },
    panelChangetIMEChange(row){
    
      this.uuidPen=row.uuid
      console.log("row",uuidPen);
    },
      panelChangetIME(value){
        console.log("va",this);
      this.formatDate(value._d)
      },
      is_Show_Change(e, row){
          // console.log("row.is_show_expira",row.is_show_expira)
          // let btn=0
          // if (row.is_show_expira=='false') {
          //   console.log("dui");
          //   btn=1
          // }else{
          //   console.log("cipwi");
          //   btn=0
          // }  
          // console.log("row.btn",btn)
          this.$http.put(`/kapaishes/${row.uuid}/gift`, {
          type: 'update',
          attributes: {
            is_show_expira: row.is_show_expira==1?1:0
          }
        }).then(res => {
          this.initList()
          // this.$iForm.hide()
        })
      },
      handleEditLog(row) {
        this.list_record = row
        this.isGiftRecord = true
      },
      handleEditLordSkuList(row) {
        this.current = row
        this.isEditLordSkuList = true
      },
      statusChange(e, row) {
        this.$http.put(`/kapaishes/${row.uuid}/gift`, {
          type: 'update',
          attributes: {
             status: e
          }
        }).then(res => {
          this.initList()
          // this.$iForm.hide()
        })
      },
      handleUpdateListWeight(row) {
        // console.log(row)
        this.$http.put(`/kapaishes/${row.uuid}/gift`, {
          type: 'update',
          attributes: {
            list_weight: this.listWeight,
          }
        }).then(res => {
          this.initList()
          row.visible = false
          this.listWeight = ''
        })
      },
      initList() {
        this.$http.get(`/kapaishes/${this.info.uuid}/gift`, {
          params: {
            activity_id: this.info.id,
            page: this.page,
            per_page: this.per_page,
          }
        }).then(res => {
          this.list = res.data.list
          this.total = res.data.item_total
        })
      },
      handleCreate() {
        this.$iForm.show({
          title: '新增集换礼包',
          frame: this.frame,
          success: (data) => {
            this.$http.post(`/kapaishes/${this.info.uuid}/gift`, {
              ...data,
            }).then(res => {
              this.initList()
              this.$iForm.hide()
            })
          },
        })
      },
      handleEdit(row) {
        this.$iForm.show({
          title: '编辑集换礼包',
          frame: this.frame,
          form: row,
          success: (data) => {
            this.$http.put(`/kapaishes/${row.uuid}/gift`, {
              type: 'update',
              attributes: {
                ...data
              }
            }).then(res => {
              this.initList()
              this.$iForm.hide()
            })
          },
        })
      },
      handleCancel() {
        this.$emit('refresh')
        this.$emit('close')
      },
      handleSave() {
        this.$emit('refresh')
        this.$emit('close')
      },
      handleDelete(row) {
        this.$confirm({
          title: '提示',
          content: `确认删除吗？`,
          onOk: () => {

            this.$http.delete(`/kapaishes/${row.uuid}/gift`).then(res => {
              this.$message.success('删除成功')
              this.initList()
            })

          }
        })


      }
    }
  }
</script>
<style lang="less" scoped>
  .thumb {
    width: 60px;
    // height: 60px;
    border-radius: 6px;
  }

  .btn-c {
    display: flex;
    // margin-top: 30px;
    padding: 0rpx 30rpx;

    .add {}

    .save {
      margin-right: 20px;
    }

    .cancel {}
  }

  .tips {
    color: gray;
    font-size: 80%;
    margin-bottom: 10px;
  }

  a-input {
    display: inline;
  }
</style>
